package file;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.Scanner;

public class FileMatchDemo {
    public static void main(String[] args) {
        //1. 输入要扫描的目录
        //2. 输入要匹配的文件内容的key
        //3. 查找该目录下, 有哪些文件内容包含了关键字key
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的目录:");
        String searchPath = scanner.nextLine();

        File searchFile = new File(searchPath);
        if (!searchFile.isDirectory()) {
            System.out.println("请输入正确的目录!!!");
            return;
        }

        System.out.println("请输入要匹配的key:");
        String key = scanner.nextLine();

        scanDir(searchFile, key);
    }

    private static void scanDir(File searchFile, String key) {
        File[] files = searchFile.listFiles();
        if (files == null || files.length == 0){
            return;
        }
        for (File f:files){
            if (f.isDirectory()){
                scanDir(f,key);
            }else{
                //如果f是文件, 而且文件的内容包含了关键字, 就打印出来路径
                if (f.isFile() && matchKey(f,key)){
                    System.out.println(f.getPath());
                }
            }
        }
    }

    private static boolean matchKey(File f, String key) {
        //把文件的内容读出来, 判断是否包含关键字
        StringBuilder builder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {
            while (true){
                char[] buf = new char[1024];
                int len = reader.read(buf);
                if (len == -1){
                    //文件读完了
                    break;
                }
//                builder.append(buf,0, len);
                //把读取的数据,放到build里面
                builder.append(new String(buf,0,len));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return builder.toString().contains(key);

    }
}
